# -*- coding:utf-8 -*-

from flask import request,jsonify,current_app,g
from ihome.utils.response_code import RET
from . import api
import datetime
from ihome.models import House,Order
from ihome.utils.common import login_required
from ihome import db

@api.route("/orders",methods = ["POST"])
@login_required
def add_order():
    data_dict = request.json
    start_date = data_dict.get("start_date")
    end_date = data_dict.get("end_date")
    house_id = data_dict.get("hid")
    # print start_date,end_date,house_id
    if not all([start_date,end_date,house_id]):
        return jsonify(errno = RET.PARAMERR,errmsg = "参数错误1")

    try:
        start_date = datetime.datetime.strptime(start_date,"%Y-%m-%d")
        end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
        assert start_date < end_date ,Exception("开始日期小于结束日期")
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg = "参数错误2")

    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询房屋失败")

    if not house:
        return jsonify(errno=RET.NODATA, errmsg="房屋不存在")

    try:
        filters = [Order.house_id==house_id,Order.begin_date<end_date,Order.end_date>start_date]
        order_count = Order.query.filter(*filters).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询房屋失败")

    if order_count>0:
        return jsonify(errno=RET.NODATA, errmsg="房屋被预定")


    days = (end_date-start_date).days
    order = Order()
    order.house_id = house_id
    order.user_id = g.user_id
    order.begin_date = start_date
    order.end_date = end_date
    order.days = days
    order.house_price = house.price
    order.amount = house.price * days

    house.order_count += 1
    try:
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    return jsonify(errno =RET.OK, errmsg = "ok")

@api.route("/user/orders")
@login_required
def get_user_order():
    user_id = g.user_id
    try:
        orders = Order.query.filter(Order.user_id == user_id).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(erron=RET.DBERR,errmsg = "查询数据失败")

    order_dict = []
    for order in orders:
        order_dict.append(order.to_dict())

    return jsonify(erron=RET.OK,errmsg="ok",data={"orders":order_dict})